import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class server {

	private static int serverport = 5050;
	private static ServerSocket serverSocket;

	// 用串列來儲存每個client
	

	// 程式進入點
	public static void main(String[] args) {
		try {
			serverSocket = new ServerSocket(serverport);
			System.out.println("Server is start.");

			// 當Server運作中時
			while (!serverSocket.isClosed()) {
				// 顯示等待客戶端連接
				System.out.println("Wait new clinet connect");

				// 呼叫等待接受客戶端連接
				waitNewPlayer();
			}

		} catch (IOException e) {
			System.out.println("Server Socket ERROR");
		}

	}

	// 等待接受客戶端連接
	public static void waitNewPlayer() {
		try {
			Socket socket = serverSocket.accept();
			System.out.println("Accept!");
			// 呼叫創造新的使用者
			 Thread client = new createNewPlayer(socket);
			 client.start();
		} catch (IOException e) {
		}

	}

	

	// 廣播訊息給其它的客戶端
	public static void castMsg(String Msg,ArrayList<Socket> players) {
		// 創造socket陣列
		Socket[] ps = new Socket[players.size()];

		// 將players轉換成陣列存入ps
		players.toArray(ps);

		// 走訪ps中的每一個元素
		for (Socket socket : ps) {
			try {
				// 創造網路輸出串流
				BufferedWriter bw;
				bw = new BufferedWriter(new OutputStreamWriter(
						socket.getOutputStream()));

				// 寫入訊息到串流
				bw.write(Msg + "\n");

				// 立即發送
				bw.flush();
			} catch (IOException e) {

			}
		}
	}
}
